package utilities;

import java.util.Random;

public class WeightedRandom {
	public WeightedRandom(double ... weights){
		this.weights = weights;
		sum = 0;
		for(int i = 0; i<weights.length; i++)
			sum += weights[i];
		this.r = new Random();
	}
	
//	public WeightedRandom(double[] weights){
//		this.weights = weights;
//		sum = 0;
//		for(int i = 0; i<weights.length; i++)
//			sum += weights[i];
//		this.r = new Random();
//	}
	
	public int next(){
		double value = r.nextDouble()*sum;
		double partial = 0;
		for(int i = 0; i<weights.length; i++){
			partial += weights[i];
			if(partial>value)
				return i;
		}
		return weights.length;
	}
	
	private double sum;
	private double[] weights;
	private Random r;
}
